<template>
  <div class="axiom-advanced-filter" :class="{ 'has-active-filters': hasActiveFilters }">
    <!-- 高级筛选侧边栏 -->
    <div 
      v-if="showAdvancedFilter" 
      class="filter-overlay"
      @click.self="handleOverlayClick"
    >
      <div class="filter-sidebar" @click.stop>
        <!-- 直接显示筛选项，移除标题区域 -->
        <div class="filter-content">
          <!-- 可滚动的筛选项区域 -->
          <div class="filter-scroll-area">
            <div class="filter-grid">
              <div
                v-for="filterItem in filterItems"
                :key="filterItem.key"
                class="filter-item"
                @click="handleFilterItemClick(filterItem)"
              >
                <AxiomText>{{ filterItem.label }}</AxiomText>
                <AxiomText 
                  v-if="getFilterDisplayValue(filterItem)" 
                  type="primary"
                >
                  {{ getFilterDisplayValue(filterItem) }}
                </AxiomText>
                <AxiomText v-else type="muted">全部</AxiomText>
              </div>
            </div>
          </div>
          
          <!-- 固定底部按钮区域 -->
          <div class="filter-actions">
            <AxiomButton type="text" @click="handleClearAll">清空筛选</AxiomButton>
            <AxiomButton type="primary" @click="handleApplyFilters">应用筛选</AxiomButton>
          </div>
        </div>
      </div>
    </div>

    <!-- 筛选器弹窗组件 -->
    <component
      v-for="filterItem in filterItems"
      :key="`sheet-${filterItem.key}`"
      :is="getFilterComponent(filterItem.type)"
      v-model:visible="filterSheetVisibility[filterItem.key]"
      v-model="filterValues[filterItem.key]"
      :title="filterItem.label"
      @confirm="handleFilterConfirm(filterItem.key, $event)"
      v-bind="getFilterProps(filterItem)"
    />
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue';
import AxiomButton from '../common/AxiomButton.vue';
import AxiomText from '../common/AxiomText.vue';
import * as filterUtils from '../../utils/filterUtils';

const props = defineProps({
  searchQuery: { type: String, default: '' },
  searchPlaceholder: { type: String, default: '搜索...' },
  filterTitle: { type: String, default: '高级筛选' },
  filterItems: { type: Array, required: true },
  defaultFilters: { type: Object, default: () => ({}) }
});

const emit = defineEmits([
  'search', 'filter-change', 'apply-filters', 
  'clear-filters', 'update:searchQuery'
]);

const internalSearchQuery = ref(props.searchQuery);
const showAdvancedFilter = ref(false);
const filterValues = ref({ ...props.defaultFilters });
const filterSheetVisibility = ref({});

props.filterItems.forEach(item => {
  filterSheetVisibility.value[item.key] = false;
});

const hasActiveFilters = computed(() => filterUtils.hasActiveFilters(filterValues.value));

watch(() => props.searchQuery, (newVal) => {
  internalSearchQuery.value = newVal;
});

watch(internalSearchQuery, (newVal) => {
  emit('update:searchQuery', newVal);
});

const getFilterDisplayValue = (filterItem) => {
  return filterUtils.getFilterDisplayValue(filterItem, filterValues.value);
};

const getFilterComponent = (type) => {
  return filterUtils.getFilterComponentName(type);
};

const getFilterProps = (filterItem) => {
  const baseProps = { ...(filterItem.props || {}) };
  if (['select', 'multi-select'].includes(filterItem.type)) {
    baseProps.options = Array.isArray(filterItem.options) ? filterItem.options : [];
  }
  if (['number-range'].includes(filterItem.type)) {
    if (filterItem.min !== undefined) baseProps.min = filterItem.min;
    if (filterItem.max !== undefined) baseProps.max = filterItem.max;
  }
  if (['date-range'].includes(filterItem.type)) {
    if (filterItem.minDate) baseProps.minDate = filterItem.minDate;
    if (filterItem.maxDate) baseProps.maxDate = filterItem.maxDate;
  }
  return baseProps;
};

const handleFilterItemClick = (filterItem) => {
  filterSheetVisibility.value[filterItem.key] = true;
};

const handleFilterConfirm = (key, value) => {
  filterValues.value[key] = value;
  filterSheetVisibility.value[key] = false;
  emit('apply-filters', { ...filterValues.value });
};

const handleOverlayClick = () => {
  showAdvancedFilter.value = false;
};

const handleClearAll = () => {
  filterUtils.clearAllFilters(filterValues.value, props.filterItems);
  internalSearchQuery.value = '';
  emit('clear-filters');
  emit('apply-filters', { ...filterValues.value });
};

const handleApplyFilters = () => {
  emit('apply-filters', { ...filterValues.value });
  showAdvancedFilter.value = false;
};

// Expose methods for parent if needed, e.g., to open the filter panel
defineExpose({
    open: () => showAdvancedFilter.value = true,
    close: () => showAdvancedFilter.value = false,
});

</script>

<style lang="scss">
@use '../../styles/components/mobile/axiom-advanced-filter';
</style> 